import React from "react";
// 导航栏组件
import MyNavBar from "../../components/common/navbar";
import { List, AutoSizer } from 'react-virtualized'
// 导入 api
import { CityListApi } from '../../api/model/cityList'
// 获取定位城市
import { getCurrentCity } from "../../utils/index";

// 路由跳转组件
import Jump from '../../components/common/jump';

// 导入样式文件
import './index.scss'

const TITLE_HEIGHT = 30
const ITEM_HEIGHT = 35

// 处理城市列表标题
function handleLrtter(letter: string): any {
  switch (letter) {
    case '#':
      return '定位城市'
    case 'hot':
      return '热门城市'
    default:
      return letter.toUpperCase()
  }
}

export default class CityList extends React.Component {
  state: any
  cityListComponent: any
  constructor(props: any) {
    super(props)

    this.state = {
      cityList: {},
      cityIndex: [],
      // 控制索引列表的高亮状态
      activeIndex: 0
    }
    // 1 创建ref对象
    // 2 将创建好的 ref 对象，添加为 List 组件的 ref 属性
    // 3 通过 ref current 属性 ，获取到组件实例，再调用组件的 scrollToRow 方法
    // 4 设置 List 组件的 scrollToAlignment 配置项值为 start，保证被点击的行出现在页面顶部
    // 5 对于点击索引无法正确定位的问题，调佣List组件的measureAllRows方法，提前计算高度来解决
    this.cityListComponent = React.createRef()
  }


  async componentDidMount() {
    await this.getCity()
    this.cityListComponent.current.measureAllRows()
  }

  async getCity() {
    // 获取城市数据
    const cityData = await CityListApi.getCity({ level: 1 })
    let cityList = {}

    cityData.body.forEach((item: any) => {
      // 获取每个城市的首字母
      let first = item.short.substr(0, 1)
      // 判断cityList 中是否有该分类
      if (cityList[first]) {
        // 如果有 直接添加
        cityList[first].push(item)
      } else {
        // 如果没有 
        cityList[first] = [item]
      }

    })

    let cityIndex = Object.keys(cityList).sort()

    // 获取热门城市列表
    const hotCity = await CityListApi.getHotCity()
    cityList['hot'] = hotCity.body
    cityIndex.unshift('hot')

    // 获取定位城市数据
    const positionCity = await getCurrentCity()

    cityList['#'] = [positionCity]
    cityIndex.unshift('#')
    // console.log(cityIndex)

    this.setState({
      cityList,
      cityIndex
    })

  }

  // 选择城市
  selectCity = (cityData) => {
    // console.log(cityData)
    localStorage.setItem('hkzf_city', JSON.stringify(cityData))
  }


  // index/索引号 isScrolling/当前项是否在滚动中 isVisible/当前项在List中是可见的 style/一定要给每一行加上 指定每一行的位置
  rowRenderer = ({ key, index, isScrolling, isVisible, style }) => {
    // console.log(this.state.cityIndex, index)
    // 获取每一行的索引
    const letter = this.state.cityIndex[index]
    const list = this.state.cityList[letter]
    // console.log(list)
    return (
      <div key={index} style={style}>
        <div style={{ height: TITLE_HEIGHT }} className="cityList_AutoSizer_title">
          {/* {letter.toUpperCase()} */}
          {handleLrtter(letter)}
        </div>
        {
          list.map((item: any) => {
            return <Jump path={-1} key={item.value}>
              <div style={{ height: ITEM_HEIGHT }} className="cityList_AutoSizer_item"
                onClick={() => {
                  this.selectCity(item)
                }}>
                {item.label}
              </div>
            </Jump>
          })
        }
        {/* <div>{this.state.cityList}</div> */}
      </div>
    )
  }

  // 计算列表的高度
  getRowHeight = ({ index }) => {
    const { cityList, cityIndex } = this.state
    //console.log(cityList[cityIndex[index]], cityIndex[index])
    // 标题高度TITLE_HEIGHT + 每一行的高度的 的和
    return TITLE_HEIGHT + cityList[cityIndex[index]].length * ITEM_HEIGHT
  }

  // 获取List组件渲染行的信息
  onRowsRendered = ({ startIndex }) => {
    // console.log(startIndex)
    if (this.state.activeIndex !== startIndex) {
      this.setState({
        activeIndex: startIndex
      })
    }

  }


  render() {
    return (
      <div className="cityList">
        <MyNavBar title="城市列表"></MyNavBar>

        <div className="cityList_AutoSizer">
          <AutoSizer>
            {({ height, width }) => (
              <List
                ref={this.cityListComponent}
                height={height}
                rowCount={this.state.cityIndex.length}
                rowHeight={this.getRowHeight}   //高度是item-name的css高度
                rowRenderer={this.rowRenderer}
                width={width}
                onRowsRendered={this.onRowsRendered}
                scrollToAlignment='start'
              />
            )}
          </AutoSizer>
        </div>

        <ul className="cityList_Indexes">
          {
            this.state.cityIndex.map((item: any, index) => {
              return <li key={index} className={index === this.state.activeIndex ? 'active' : ''}
                onClick={() => this.cityListComponent.current.scrollToRow(index)}>
                {item === 'hot' ? '热' : item}
              </li>
            })
          }

        </ul>

      </div>

    )
  }
}